package com.yuyou.fn.educational.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.toolkit.IdWorker;
import com.yuyou.fn.platform.entity.Oauth;
import com.yuyou.fn.platform.service.IOauthService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.yuyou.fn.platform.mapper.CustomerUserMapper;
import com.yuyou.fn.platform.entity.CustomerUser;
import com.yuyou.fn.educational.service.ICustomerUserService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 *
 * CustomerUser 表数据服务层接口实现类
 *
 */
@Service
public class CustomerUserServiceImpl extends SuperServiceImpl<CustomerUserMapper, CustomerUser,Long> implements ICustomerUserService {


    @Resource
    private IOauthService oauthService ;

    @Transactional
    @Override
    public CustomerUser loginFormWx(String openId, String nickname , String sex, String province, String city, String avatar) {

        Oauth oauth = oauthService.findByOpenId(openId);

        if(oauth == null ){

            CustomerUser customerUser = new CustomerUser();
            if(StringUtils.isNotEmpty(avatar)){
                customerUser.setAvatarUrl(avatar);
            }

            if(StringUtils.isNotEmpty(province)){
                StringBuilder sb  = new StringBuilder() ;
                sb.append(province);
                if(StringUtils.isNotEmpty(city)){
                    sb.append(" ").append(city);
                }
                customerUser.setLocation(sb.toString());
            }

            if(StringUtils.isNotEmpty(sex)){
                customerUser.setSex("男".equals(sex) ? 1 : 2);
            }

            if(StringUtils.isNotEmpty(nickname)){
                customerUser.setNickname(nickname);
            }

            customerUser.setUsername("wx_" + IdWorker.getId() );
            customerUser.setPassword(DigestUtils.md5Hex("yuyou100"));
            insertSelective(customerUser);
            oauthService.saveOauth( customerUser.getUserId(),openId,1 ) ;
            return customerUser ;

        }else{
            return findById(oauth.getUserId()) ;
        }

    }

    @Override
    public void updatePersonMessage(CustomerUser customerUser) {
        Example<CustomerUser> example=CustomerUser.createExample();
        example.createCriteria().andEqualTo("userId",customerUser.getUserId());
        this.updateSelectiveByExample(customerUser,example);
    }
}